﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ClassObjectPool<T> where T : class, new()
{

    protected Stack<T> m_Pool = new Stack<T>();

    protected int m_MaxCount = 0;

    protected int m_NoRecyleCount = 0;

    public ClassObjectPool(int maxcount)
    {
        m_MaxCount = maxcount;
        for (int i = 0; i < maxcount; i++)
        {
            m_Pool.Push(new T());
        }
    }

    //从池里面取类对象  如果为空是否new出来
    public T Spawn(bool createIfPoolEmpty = true)
    {
        if (m_Pool.Count > 0)
        {
            T rtn = m_Pool.Pop();
            if (rtn == null)
            {
                if (createIfPoolEmpty)
                {
                    rtn = new T();
                }
            }
            m_NoRecyleCount++;
            return rtn;
        }
        else
        {
            if (createIfPoolEmpty)
            {
                T rtn = new T();
                m_NoRecyleCount++;
                return rtn;
            }
        }
        return null;
    }

    //回收类对象
    public bool Recyle(T obj)
    {
        if (obj == null)
        {
            return false;
        }
        m_NoRecyleCount--;
        if (m_Pool.Count >= m_MaxCount && m_MaxCount > 0)
        {
            obj = null;
            return false;
        }
        m_Pool.Push(obj);
        return true;
    }
	
}
